package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.commons.utils.UserHolder;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.CountsVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.controller.UserFreezeService;
import com.tanhua.server.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;

@Service
@Slf4j
public class Userservice {
    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserLikeApi userLikeApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private UserFreezeService userFreezeService;

    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private MqMessageService mqMessageService;

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private RecommendUserApi recommendUserApi;




    public void sendMsg(String phone) {

        User user = userApi.findByMobile(phone);
        if(user!=null){
            userFreezeService.checkUserStatus("1",user.getId());
        }
        String code = RandomStringUtils.randomNumeric(6);
        log.info("短信验证码为:{}", code);
        redisTemplate.opsForValue().set("CHECK_CODE_" + phone, code, Duration.ofMillis(50000));
    }

    public Map loginVerification(String phone, String code) {
        //1、从redis中获取下发的验证码
        String redisCode = (String) redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        log.info("redis中的验证码信息:{}", redisCode);
        //2、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //验证码无效
            throw new BusinessException(ErrorResult.loginError());
        }
        //3、删除redis中的验证码
        redisTemplate.delete("CHECK_CODE_" + phone);
        //4、通过手机号码查询用户
        User user = userApi.findByMobile(phone);
        boolean isNew = false;
        //5、如果用户不存在，创建用户保存到数据库中
        String type ="0101";
        if (user == null) {
            type="0102";
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;
            String hxUser = "hx" + user.getId();
            Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if (create) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }
        }
        mqMessageService.sendLogMessage(user.getId(),type,"user",null);
        //6、通过JWT生成token(存入id和手机号码)
        Map tokenMap = new HashMap();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", phone);
        String token = JwtUtils.getToken(tokenMap);
        //7、构造返回值
        Map retMap = new HashMap();
        retMap.put("token", token);
        retMap.put("isNew", isNew);

        return retMap;
    }

    public boolean checkVerificationCode(String verificationCode) {
        String mobile = UserHolder.getMobile();
        //1、从redis中获取验证码
        String redisCode = (String) redisTemplate.opsForValue().get("CHECK_CODE_" + mobile);
        log.info("redisCode:{}", redisCode);
        log.info("前端传来的验证码:{}", verificationCode);
        if (!redisCode.equals(verificationCode)) {
            //验证码无效
            throw new BusinessException(ErrorResult.loginError());
        }
        //3、删除redis中的验证码
        redisTemplate.delete("CHECK_CODE_" + mobile);
        return true;
    }

    public void updatephone(String phone) {
        //先查手机号是否已经注册存在
        User user = userApi.findByMobile(phone);
        if (user != null) {
            throw new BusinessException(ErrorResult.mobileError());//用户已经注册
        }
        //修改用户手机号
        User user1 = new User();
        user1.setId(Long.valueOf(UserHolder.getUserId()));
        user1.setMobile(phone);
        log.info("用户数据:{}", user1);
        userApi.update(user1);
    }
    //查找喜欢互相喜欢喜欢我的
    public CountsVo findCount() {
        Long userId = UserHolder.getUserId();
        //喜欢我
       Integer loveCount = userLikeApi.findLikeme(userId);
       //我喜欢
       Integer fanCount = userLikeApi.MeLike(userId);
       //互相喜欢
       Integer eachLoveCount = userLikeApi.eachLove(userId);
         CountsVo vo=new CountsVo();
         vo.setEachLoveCount(eachLoveCount);
         vo.setFanCount(fanCount);
         vo.setLoveCount(loveCount);
         return vo;
    }
    //1 互相喜欢
    //2 我喜欢
    //3 喜欢我
    //4 谁看过我
    public PageResult friendsType(int type, int page, int pagesize) {
        Long userId = UserHolder.getUserId();
        switch (type){
            case 1:
                List<Long> userIds=friendApi.findById(page,pagesize,userId);
                Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds, null, null);
                List<UserInfoVo> vos =new ArrayList<>();
                for (Long id : userIds) {
                    UserInfoVo vo =new UserInfoVo();
                    UserInfo userInfo = userInfoMap.get(id);
                    BeanUtils.copyProperties(userInfo,vo);
                    vo.setMatchRate(new Random().nextInt(30)+70);
                    vo.setAlreadyLove(true);
                    vos.add(vo);
                }
                return new PageResult(page,pagesize,0,vos);
            case 2:
                List<UserLike> userLike = userLikeApi.findUserLike(page, pagesize, userId);

            case 3:
            case 4:

        }
    }


}
